package com.javaee.my.user;

import com.javaee.interceptor.Utils.loginCookies;
import com.javaee.interceptor.entity.Member;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
/**
 * 登录servlet
 */

@WebServlet("/login")
public class HelloController extends HttpServlet implements BaseControllerApi{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置返回的头信息
        //当勾选记住的时候，判断是否有cookie，决定创建cookie，最后转发到index.jsp当中
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        HttpSession session = req.getSession();
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //0.先判断session中是否有这样的值，如果有，表示此账号已经被注册了，不能进行注册登陆
        //1.然后再把值拿过来进行判断，是否有这样的值，如果有，则表示已经注册，放行通过。
        for(Member member : members) {
            if (username.equals(member.getUsername()) && password.equals(member.getPassword())) {
                System.out.println("校验成功！");
                //完成对用户名和密码的cookie操作
                loginCookies.login(req, resp);
                //将信息放入到session会话当中去
                session.setAttribute("username",member.getUsername());
                session.setAttribute("password",member.getPassword());
                //转发请求到结果页面
                req.getRequestDispatcher("res.jsp").forward(req, resp);
                return;
            }
        }
            System.out.println("校验失败，请重新登陆！");
            req.getRequestDispatcher("404.jsp").forward(req,resp);
            return;
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}
